import { computed, defineComponent, ref, Ref, watch } from 'vue';
import {
  getDataPickerProps,
  getEditorEmits,
  renderString,
  useFocusAndBlur,
  useNamespace,
} from '@ibiz-template/vue3-util';
import './ibiz-picker-link.scss';
import { PickerEditorController } from '../picker-editor.controller';

export const IBizPickerLink = defineComponent({
  name: 'IBizPickerLink',
  props: getDataPickerProps<PickerEditorController>(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('picker-link');

    const c = props.controller!;

    const curValue: Ref<string> = ref('');

    // 是否显示表单默认内容
    const showFormDefaultContent = computed(() => {
      if (
        props.controlParams &&
        props.controlParams.editmode === 'hover' &&
        !props.readonly
      ) {
        return true;
      }
      return false;
    });

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal && newVal !== oldVal) {
          if (c.model.valueType === 'OBJECT') {
            curValue.value = newVal
              ? (newVal as IData)[c.objectNameField as string]
              : '';
          } else {
            curValue.value = newVal as string;
          }
        }
      },
      { immediate: true },
    );

    // 处理视图关闭，往外抛值
    const handleOpenViewClose = (data: IData) => {
      // 处理值项和本身的值
      const item: IData = {};
      Object.assign(item, data);
      Object.assign(item, {
        [c.keyName]: item[c.keyName] ? item[c.keyName] : item.srfkey,
        [c.textName]: item[c.textName] ? item[c.textName] : item.srfmajortext,
      });
      if (c.valueItem) {
        emit('change', item[c.keyName], c.valueItem);
      }
      if (c.model.valueType === 'OBJECT') {
        emit('change', c.handleObjectParams(item));
      } else {
        emit('change', data[c.textName]);
      }
    };

    // 打开数据链接视图
    const openLinkView = async () => {
      const res = await c.openLinkView(props.data!);
      if (res) {
        handleOpenViewClose(res[0]);
      }
    };

    // 聚焦失焦事件
    const { componentRef: editorRef } = useFocusAndBlur(
      () => emit('focus'),
      () => emit('blur'),
    );

    const valueText = computed(() => {
      return renderString(curValue.value);
    });

    watch(
      valueText,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          emit('infoTextChange', newVal);
        }
      },
      { immediate: true },
    );

    return { ns, openLinkView, curValue, editorRef, showFormDefaultContent };
  },
  render() {
    return (
      <div
        class={[
          this.ns.b(),
          this.readonly ? this.ns.m('readonly') : '',
          this.ns.is('show-default', this.showFormDefaultContent),
        ]}
        ref='editorRef'
      >
        <a onClick={this.openLinkView}>{this.curValue}</a>
      </div>
    );
  },
});
